import React from 'react';
import { Route, withRouter, Switch, } from 'react-router-dom';
import { observer, inject } from 'mobx-react';
import { Schedule, Icon, Flex, Tools,List,TextareaItem,Bubble} from 'weaver-mobile';
import { RouteLayout } from 'weaver-mobile-page';
import Detail from '../detail/index';
import ItemCard from '../../public/ItemCard'
import Create from '../create/index';
import Report from '../report/index';
const getLabel = Tools.getLabel;
const HEIGHT = 0.32* window.innerHeight;

const store = [
  'calendarStore',
  'viewWorkplanStore',
  'createStore'
];
@inject(...store)
@withRouter
@observer
export default class Workplan extends React.Component {
   constructor(props) {
    super(props);
    this.state = {
      yuyinfirstMessage: false,
      key: '1',
      visible: false,
      selected: '',
      span: [4, 1],
      voiceORcreate: true,
      isStart: true,
      vHeight: 0,
      siriHeight: 60,
      isRun: false,
      valuestring: '',
      siristart: true,
      borderWidth: 1,
      isTextarea: false, //
      extra: {
      },
    };
  }

  componentWillMount() {
    if(localStorage && localStorage.getItem('yuyinfirstMessage') === null) {
      // 仅仅初次进入会出现语音使用引导
      this.setState({yuyinfirstMessage: true});
      localStorage.setItem('yuyinfirstMessage',true);
      setTimeout(() => {
        // 5s后消失
        this.setState({yuyinfirstMessage: false});
      }, 5000);
    }else{
      // this.setState({yuyinfirstMessage: false});
    }
  }
  
  componentWillReceiveProps(nextProps) {
    const { location: { pathname: nxetP }, history: h } = nextProps;
    const { location: { pathname: p } } = this.props;
    const reg = /\/[^\\/]+$/;
    if(true) { // 指定人员时,禁止再次请求接口
      if (nxetP !== p && nxetP.replace(reg, '') !== p.replace(reg, '') && h.action === 'POP') {
        const {selectDate} = this.props.calendarStore;
        if(p.indexOf('detail')>0 || p.indexOf('create')>0){
          // 刷新数据
          this.getCalendarInfo(selectDate);
          this.getWorkplanDatasList(selectDate);
        }
      }
    }
  }
  
  componentDidMount() {
    let curPathName = this.props.location.pathname
    if(curPathName=="/calendar/myCalendar"){
      window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: getLabel(18480, '我的日程') })
    }else if(curPathName=="/calendar/allCalendar"){
      window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: getLabel(27910, '所有日程') })
    }
    const {selectDate,setState,changeUserInfo,} = this.props.calendarStore;
    let datestr = '';
    if(localStorage && localStorage.selectDate) {
      datestr = localStorage.selectDate;
    }else{
      datestr = selectDate;
    }
    localStorage.setItem('routeType',this.props.type);
    changeUserInfo(localStorage.userId, localStorage.userName)
    setState({selectDate: datestr, freshCalendar: this.freshCalendar});
    this.getCalendarInfo(selectDate);
    this.getWorkplanDatasList(selectDate);
    this.checkJsApi(this.setTimeVoiceCreate); // yesVoice判断是否有语音功能，存在可语音创建日程(绑定事件)
    // this.createWorkplan()// 仅pc调试使用
  }

  componentWillUnmount() {
    // 卸载组件
    const { setState, } = this.props.calendarStore;
    // localStorage.removeItem('selectDate');
    setState({conditionsInfo: [],userName: ''});
  }
  componentWillReceiveProps(nextProps){
    let prePathName = this.props.location.pathname
    let curPathName = nextProps.location.pathname
    if(curPathName&&curPathName!==prePathName){
      if(curPathName=="/calendar/myCalendar"){
        window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: getLabel(18480, '我的日程') })
      }else if(curPathName=="/calendar/allCalendar"){
        window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: getLabel(27910, '所有日程') })
      }
    }
  }
  componentDidUpdate() {
    const { setState } = this.props.calendarStore;
    let height = this.getHeight();
    if(height) {
      setState({itemCardHeight: height});
    }
  }

  isVoice = () => {
    // 切换麦克风和新建
    let div = this.refs.sheduleFooter;
    let XI = 0;
    let XII = 0;
    const fnStart = (ev) => {
      XI = ev.changedTouches[0].pageX;
    }
    const fnEnd = (ev) => {
      XII = ev.changedTouches[0].pageX  
      if(Math.abs(XII - XI) > 10) {
        const {voiceORcreate} = this.state;
        let t = voiceORcreate ? false : true;
        this.setState({voiceORcreate: t,vHeight: 0},this.changeVoice);
      }
    }
    div.addEventListener('touchstart',fnStart,false);
    div.addEventListener('touchend',fnEnd,false);
  }

  checkJsApi = (callback) => {
    const {setState} = this.props.calendarStore;
    window.em && window.em.checkJsApi({
      jsApiList: ['continueSpeech','stopVoice'], // 需要检测的js接口列表
      success: function(res) {
        setState({
          yesVoice:  res['checkResult']['continueSpeech'], // 判断是否有语音功能
          continueSpeech: res['checkResult']['continueSpeech'],
          stopVoice: res['checkResult']['stopVoice'],
        },callback);
      }
    })
  }

  setTimeVoiceCreate = () => {
    setTimeout(() => {
      this.createWorkplan();
    }, 500);
  }

  createWorkplan = () => {
    let createVoice = this.refs.createVoice;
    let BEGIN = 0;
    let END = 0;
    let timer = {};
    let SW9 = createVoice ? new window.SiriWave({
          container: this.refs.voiceSiri,
          autostart: false,
          amplitude: 0.2,
          style: 'ios9'
        }) : '';

    const speeching = () => {
      const {setState,voiceContent} = this.props.calendarStore;
      window.em && window.em.continueSpeech({'changeVoice':function (argument) {
          if(argument/10 > 1) {
            SW9.setAmplitude(1);
          }else{
            SW9.setAmplitude(argument/10);
          }
        },'continueSpeechend':function (argument) { // 录音结束调用
        },'onContinueSpeech':function (argument) {
          let currentStr = '';
          if(typeof(argument) === 'string'){ // ios
            currentStr = JSON.parse(argument)['result'] ? JSON.parse(argument)['result'] : '';
          }else{ // android
            currentStr = argument['result'] ? argument['result'] : '';
          }
          setState({voiceContent: voiceContent+currentStr});
        },'success':function (argument) {
          // alert('success')
          setState({voiceSuccess: true})
        },'fail':function (argument) {
          setState({voiceSuccess: false,siriVisible: 'none',orVoice: true})
        },'cancel':function (argument) {
        /* body... */
        },'complete':function (argument) {
        /* body... */
        }
      })
    }
    const stopvoice = () => {
      window.em && window.em.stopVoice({'success':function (argument) {
        },'fail':function (argument) {
        },'cancel':function (argument) {
        },'complete':function (argument) {
        }
      })
    }
    const fnStart = () => {
      BEGIN = new Date().getTime();
      const {vHeight,} = this.state;
      const {voiceSuccess,setState} = this.props.calendarStore;
      timer = setTimeout(() => {
        speeching();// 开始录音,防止录音不全
        voiceSuccess && setState({siriVisible: 'block'}); // 开始波纹图
        if(vHeight === HEIGHT) {
          voiceSuccess && SW9.start();
        }else{
          // 第一次进入避免直接页面获得焦点
          voiceSuccess ? this.setState({vHeight: HEIGHT,isTextarea: true,borderWidth: 0},SW9.start()) // 开启语音
                        : this.setState({vHeight: HEIGHT,isTextarea: true,borderWidth: 0});
        }
      }, 250);
    }
    const fnEnd = () => {
      const {} = this.state;
      const {voiceSuccess,setState,orVoice} = this.props.calendarStore;
      END = new Date().getTime();
      setState({orVoice: true});
      clearTimeout(timer);
      if(END-BEGIN < 250) {
        // 点击
        !orVoice && this.createBtn();
        !orVoice && setState({orVoice: false});
      }else{
        voiceSuccess && stopvoice();
        SW9.setAmplitude(0.1);
        SW9.stop();
        setState({siriVisible: 'none'}); // 结束波纹图
      }
    }
    if (createVoice) {
      createVoice.addEventListener('touchstart',fnStart,false);
      createVoice.addEventListener('touchend',fnEnd,false);
    }
  }

  freshCalendar = (bool) => {
    let date = localStorage.getItem('selectDate');
    if(bool) {
      this.getCalendarInfo(date);
      this.getWorkplanDatasList(date);
    } else {
      this.getCalendarInfo();
      this.getWorkplanDatasList();
    }
  }

  handleSelect = (opt) => {
    this.setState({
      visible: false,
      selected: opt.props.value,
    });
  }

  handleVisibleChange = (visible) => {
    this.setState({
      visible,
    });
  };

  getHeight = () => {
    let tabheight = this.props.tabHeight; // 是否有tab标签
    let HH = window.innerHeight;
    // let HH = document.body.clientHeight;
    // let scheduleContent = document.getElementsByClassName('schedule-content')[0];
    let scheduleCalendar = document.getElementsByClassName('am-schedule')[0];
    if(scheduleCalendar) {
      return tabheight ? HH - scheduleCalendar.clientHeight - 50*window.getThemeVars()['hd'] - tabheight : HH - scheduleCalendar.clientHeight - (50 +10)*window.getThemeVars()['hd'];
    } 
  }

  getCalendarInfo = (date) => {
    const type = this.props.type;
    const { getMyWorkplanDatas, getAllWorkplanDatas, userID} = this.props.calendarStore;
    type === 'allCalendar' && getAllWorkplanDatas({selectDate: date, viewType: 3, isCalendar: '1'});
    type === 'myCalendar' && getMyWorkplanDatas({selectDate: date, viewType: 3, isCalendar: '1'});
    type !== 'myCalendar' && type !== 'allCalendar' && getMyWorkplanDatas({selectDate: date, viewType: 3, selectUser: userID, isCalendar: '1'});
  }

  getWorkplanDatasList = (date) => {
    const type = this.props.type;
    const { getMyWorkplanDatas, getAllWorkplanDatas, userID, setState} = this.props.calendarStore;
    const {setParams} = this.props.createStore;
    setState({selectDate: date});
    setParams({selectDate: date});
    localStorage && localStorage.setItem('selectDate', date);
    type === 'allCalendar' && getAllWorkplanDatas({selectDate: date, viewType: 1, isCalendar: '0'});
    type === 'myCalendar' && getMyWorkplanDatas({selectDate: date, viewType: 1, isCalendar: '0'});
    type !== 'myCalendar' && type !== 'allCalendar' && getMyWorkplanDatas({selectDate: date, viewType: 1, selectUser: userID, isCalendar: '0'});
  }

  viewDetail = (id,beginDate,beginTime,endDate,endTime) => {
    let pathstr = window.location.hash && window.location.hash.split('#');
    let {changeWorkplanID,setParams} = this.props.viewWorkplanStore;
    const { userName } = this.props.calendarStore;
    changeWorkplanID(id);
    setParams({beginDate: beginDate,beginTime: beginTime,endDate: endDate,endTime: endTime})
    localStorage.setItem('workid',id)
    if(userName === ''){
      let type = this.props.type;
      localStorage.setItem('routeType',type); // 记录路由类型
      // this.props.history.push(`${pathstr[1]}/detail/index`)
    }else{
      localStorage.setItem('routeType','schdule'); // 记录路由类型
      // this.props.history.push({pathname:`/calendar/schdule/detail/index`})
    }
    this.props.history.push(`${this.filterURL(pathstr[1])}/detail/index`)
  }

  getExtraTitle = () => {
    // const { userName } = this.props.calendarStore;
    let userName = localStorage.userName;
    let tabs = localStorage.workplanTabs;
    if(userName && (tabs==='subordinate' || tabs==='myFllow')) {
      // 单独查看他人(下属或关注)日程时,日历上显示人员姓名  /calendar/myFllow/schdule
      let pathName = this.props.location.pathname
      if(pathName=="/calendar/subordinate/schdule"||pathName=="/calendar/myFllow/schdule"){
        window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: userName + getLabel(384891,'的日程') })
      }
      return userName + getLabel(384891,'的日程');
    }else{
      if(tabs === 'allCalendar' && window.location.hash.split('#')[1] === '/calendar/appointhrm/schdule'){
        window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: userName + getLabel(384891,'的日程') })
        // 所有日程--指定人员日程日历上也需显示人员姓名
        return userName + getLabel(384891,'的日程');
      }else{
        return '';
      }
    }
  }

  createBtn = (e) => {
    const { setParams } = this.props.createStore;
    let pathstr = window.location.hash && window.location.hash.split('#');
    setParams({isEdit: false,createDisabled: false})
    this.props.history.push(`${this.filterURL(pathstr[1])}/create`)
    return false;
  }

  filterURL = (url) => {
    const reg = /\?.*/;   // 删除？后的所有字符
    return url.replace(reg,'');
  } 

  setInfo = () => {
    const { conditionsInfo, allconditionsInfo } = this.props.calendarStore;
    const type = this.props.type;
    
    if(type === 'allCalendar') {return allconditionsInfo;}
    if(type === 'myCalendar' || (type !== 'myCalendar' && type !== 'allCalendar')) {return conditionsInfo;}
  }
  setList = () => {
    const { conditionsList,allconditionsList } = this.props.calendarStore;
    const type = this.props.type;
    
    if(type === 'allCalendar') {return allconditionsList;}
    if(type === 'myCalendar' || (type !== 'myCalendar' && type !== 'allCalendar')) {return conditionsList;}
  }

  changeBackground = (param) => {
    return param?window.getThemeVars()['less']['brand-primary'] : '#D8D8D8';
  }

  changeVoiceStr = (v) => {
    const {setState} = this.props.calendarStore;
    setState({voiceContent: v})
  }

  cancelVoice = () => {
    const {setState} = this.props.calendarStore;
    this.setState({vHeight: 0,borderWidth: 1,siristart: false});
    setState({voiceContent: '',orVoice: false,});
  }

  submitVoice = () => {
    const { addByWord, setParams } = this.props.createStore;
    const { voiceContent,setState,semanticStatus, getSemanticUrlAndParam } = this.props.calendarStore;
    if(voiceContent && voiceContent !== ''&& voiceContent !== ' ') {
      setParams({voiceCreateLoading: false});
      if (!semanticStatus) {
        getSemanticUrlAndParam(voiceContent, this.freshCalendar);
      } else {
        addByWord(voiceContent,this.freshCalendar); // 根据语音创建日程
      }
      this.setState({vHeight: 0,borderWidth: 1,siristart: false,voiceContent: ''});
      setState({voiceContent: '',orVoice: false});
    }else{
      Bubble.error(getLabel(500282,'您没有说话'),1,{top: '80%'});
    }
  }

  getLoading = () => {
    return (
      <div className='loaidng-icon' key='loading'>
        <Icon type='loading' size='lg'/>
      </div>
    );
  }

  clickReport = () => {
    const { pathname } = this.props.location;
    this.props.history.push(`${pathname}/report`)
  }

  clickMyWorkplan = () => {
    const { pathname } = this.props.location;
    if (pathname.indexOf('myCalendar') > -1) {

    } else {
      this.props.history.push('/calendar/myCalendar');
    }
  }

  getFooterLeft = () => {
    const { pathname } = this.props.location;
    let labelActive = '';
    if (pathname.indexOf('myCalendar') > -1) {
      labelActive = 'active';
    } else {
      labelActive = '';
    }
    return (
      <div className={`${labelActive} left`} onClick={(e) => {this.clickMyWorkplan()}} >
        <Icon  type={'my-meeting'} size='sm' onClick={(e) => {}} />
        <div className='label'>{getLabel(18480,'我的日程')}</div>
      </div> 
    );
  }

  getFooterRight = () => {
  
    return (
      <div className={`right`} onClick={(e) => {this.clickReport()}} >
        <Icon  type={'blog-report-form'} size='sm' />
        <div className='label'>{getLabel('15101','报表')}</div>
      </div>
    );
  }

  reportList = () => {
    return [
      {
        key: 'oneWeekWorkplan',
        name: getLabel('503461','一周日程安排') 
      },
      {
        key: 'workPlanViewList',
        name: getLabel('33959','日程一览表') 
      },
    ];
  }

  // getLayoutFooter = () => {
  //   let { selectDate,weekStart,voiceContent,yesVoice,siriVisible,orVoice,isInit,semanticStatus,itemCardHeight} = this.props.calendarStore;
  //   const { vHeight,borderWidth,isTextarea,yuyinfirstMessage, } = this.state;
  //   let maskHeight = vHeight === HEIGHT ? window.innerHeight-HEIGHT-50*window.getThemeVars()['hd'] : 0;
  //   // let voiceSiriHeight = 0.46*HEIGHT;
  //   yesVoice = yesVoice || true;
  //   return (
  //     <div>
  //       { // 仅新建功能
  //         !yesVoice && <div className="shedule-footer" ref='sheduleFooter' style={{WebkitUserSelect: 'none'}}>
  //           <Flex  justify='start'>
  //             <Flex.Item>
  //               {this.getFooterLeft()}
  //             </Flex.Item>
  //             <Flex.Item>
  //               {<div className='icon create'><Icon  type={'blog-gengduo'} size='lg' onClick={(e) => {this.createBtn(e)}} /></div> }
  //             </Flex.Item>
  //             <Flex.Item>
  //               {this.getFooterRight()}
  //             </Flex.Item>
  //           </Flex>
  //         </div>}

  //       {vHeight === HEIGHT && <div className='voiceMask' style={{height: maskHeight}} onClick={() => {this.cancelVoice()}}></div>}
  //       {yesVoice && <div className='voice-area' ref='voiceArea' style={{height: vHeight}}>
  //         <div className='voiceText'>
  //           {isTextarea && <List>
  //             <TextareaItem
  //               value={voiceContent}
  //               placeholder={getLabel(500283,"请按住说话")}
  //               onChange={v => this.changeVoiceStr(v)}
  //               rows={3}
  //             />
  //           </List>}
  //         </div>
  //         <div className='voiceSiriArea'>
  //           {<div className='voiceSiri' ref='voiceSiri' style={{display: siriVisible}}></div>}
  //         </div>
  //       </div>}
  //       {/*  */}
  //       {yesVoice && yuyinfirstMessage && <div className='firstMessage'>
  //           <div className='aaa'></div>
  //           <div>{getLabel(500284,'长按语音输入哦')}</div>
  //           <div className='arrow'></div>
  //         </div>}
  //       {yesVoice && <div className="shedule-footer" style={{WebkitUserSelect: 'none', borderTopWidth: borderWidth}}>
  //         <Flex  justify='start'>
  //           <Flex.Item>
  //             {vHeight === HEIGHT &&<div className='voiceButton voiceButton-left' onClick={() => this.cancelVoice()}>{getLabel(386789,'取消')}</div>}
  //             {vHeight != HEIGHT && this.getFooterLeft()}
  //           </Flex.Item>
  //           <Flex.Item>
  //             <div className='icon create' ref='createVoice'>
  //               {!orVoice && <Icon  type={'add-voice'} size='lg' />}
  //               {orVoice && <div className='icon icon-voice'><Icon type={'voice-1'} color='#fff' size='md' onClick={() => {}} /></div>}
  //             </div>
  //           </Flex.Item>
  //           <Flex.Item >
  //             {vHeight === HEIGHT &&<div className='voiceButton voiceButton-right' onClick={() => this.submitVoice()}>{getLabel(386788,'确定')}</div>}
  //             {vHeight != HEIGHT && this.getFooterRight()}
  //           </Flex.Item>
  //         </Flex>
  //       </div>}
  //     </div>
  //   );
  // }

  render() {
    let { selectDate,weekStart,voiceContent,yesVoice,siriVisible,orVoice,isInit,semanticStatus,itemCardHeight} = this.props.calendarStore;
    const { vHeight,borderWidth,isTextarea,yuyinfirstMessage, } = this.state;
    let maskHeight = vHeight === HEIGHT ? window.innerHeight-HEIGHT-50*window.getThemeVars()['hd'] : 0;
    // let voiceSiriHeight = 0.46*HEIGHT;
    yesVoice = yesVoice;
    const { pathname } = this.props.location;
    const detailVisible = pathname.indexOf('/report/workPlanViewList') > -1 ? false : true; // 控制日程一览表查看详情时，跳转该路由
    return (
      <div className="schedule-content">   
        {!isInit?
          this.getLoading()
          :
          <Schedule
            defaultDate={(selectDate===''||selectDate===null) ? new Date():new Date(selectDate)}
            // defaultDate={selectDate===''?localStorage.getItem('selectDate')?new Date(localStorage.getItem('selectDate')):new Date():new Date(selectDate)}
            extraTitle={this.getExtraTitle()}
            dateExtra={this.setInfo()}
            weekStart={weekStart}
            onMonthChange={(month, range, title) =>
              new Promise((resolve) => {
                setTimeout(() => {
                  this.setState({
                    extra: {
                      [range[0]]: { info: true },
                      [range[1]]: { info: true },
                    },
                  });
                  this.getCalendarInfo(month[0])
                  resolve();
                }, 100);
              })
            }
            onSelect={v => {this.getWorkplanDatasList(v)}}
          />}
        {!isInit?'':<div className="no-data-content" style={{height: itemCardHeight, overflow: 'auto',WebkitOverflowScrolling: 'touch',}}>
          <ItemCard datas={this.setList()} onRowClick={this.viewDetail} dispalyHeight={itemCardHeight}/>
        </div>}
        {/* {yesVoice && !voiceORcreate && isStart && <div className='voice-area' ref='voiceArea' style={{height: vHeight}}></div>} */}
     
        <Switch>
          {detailVisible && <Route
            key="workplanDetail"
            path="**/detail" // 匹配： .../detail  格式的路由地址
            render={()=>(
              <RouteLayout>
              <div key="calendarDetail" className="wm-route-layout wm-demo-route-layout-page">
                <Detail />
              </div>
              </RouteLayout>
            )}
          />}
          <Route 
            key="create"
            path="**/create"
            breadcrumbName="新建日程"
            render={() => (
              <div className="wm-route-layout">
                  <Create key='create'/>
              </div>
            )}
          />
          <Route 
            key="report"
            path="**/report"
            breadcrumbName="报表"
            render={() => (
              <div className="wm-route-layout" style={{height: 'calc(100% - 50px)'}}>
                <Report history={this.props.history} reportList={this.reportList()}/>
              </div>
            )}
          />
        </Switch>
      </div>
    );
  }
}